<template>
	<div class="user-content">
		<el-form :inline="true" :model="searchForm" class="search">
			<el-form-item label="用户名">
				<el-input v-model="searchForm.username" placeholder="用户名"></el-input>
			</el-form-item>
			<el-form-item label="姓名">
				<el-input v-model="searchForm.name" placeholder="姓名"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="queryUserListByPage()">查询</el-button>
				<el-button type="primary" @click="addUpdateUser(null)">新增</el-button>
				<el-button type="primary" @click="deleteUserList">删除</el-button>
			</el-form-item>
		</el-form>
		<div class="table">
			<el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55">
				</el-table-column>
				<el-table-column fixed prop="username" label="用户名">
				</el-table-column>
				<el-table-column prop="name" label="姓名">
				</el-table-column>
				<el-table-column prop="gender" label="性别">
				</el-table-column>
				<el-table-column prop="email" label="邮箱">
				</el-table-column>
				<el-table-column prop="address" label="地址">
				</el-table-column>
				<el-table-column fixed="right" label="操作">
					<template slot-scope="scope">
						<el-button type="text" @click="addUpdateUser(scope.row)">编辑</el-button>
						<el-button type="text" @click="allotRole(scope.row)">分配角色</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
			:page-sizes="[10,50, 100, 200, 500, 1000]" :page-size="pageSize"
			layout="total, sizes, prev, pager, next, jumper" :total="total" class="pagina">
		</el-pagination>
		<UserSaveUpdateVue ref="child" @refresh="refreshPage"></UserSaveUpdateVue>
		
		<el-dialog :title="roleTreeTitle" :visible.sync="roleDialogvisible">
			<el-tree ref="roleTree" :data="treeData" show-checkbox node-key="id" :props="defaultProps" :before-close="closeRoleTree" >
			</el-tree>
			<el-button type="primary" @click="saveUserRole">确定</el-button>
		</el-dialog>
	</div>
</template>

<script>
	import {
		Message
	} from 'element-ui';
	import {
		queryUsersByPage,
		deleteUsers,
		getRoleTree,
		saveUserRole,
		queryAllotedRole
	} from './api';
	import UserSaveUpdateVue from './UserSaveUpdate.vue';
	import Qs from 'qs';
	export default {
		components: {
			UserSaveUpdateVue,
			saveUserRole
		},
		data() {
			return {
				tableData: [],
				searchForm: {
					username: '',
					name: ''
				},
				currentPage: 1,
				pageSize: 10,
				total: 0,
				childData: {
					visible: false,
					title: '',
					userForm: {}
				},
				multipleSelection: [],
				roleDialogvisible: false,
				treeData: [],
				defaultProps: {
					children: 'children',
					label: 'label'
				},
				roleTreeTitle: "分配角色",
				allotUserId: '', //分配角色ID
			}
		},
		mounted() {
			this.queryUserListByPage();
			this.queryRoleTreeList();
		},
		methods: {
			// handleClick(row) {
			// 	console.log(row);
			// },
			//改变每页现实条数
			handleSizeChange(val) {
				this.pageSize = val
				this.queryUserListByPage();
			},
			//改变当前页数
			handleCurrentChange(val) {
				this.currentPage = val;
				this.queryUserListByPage();
			},
			//分页查询数据
			queryUserListByPage() {
				let params = {
					page: this.currentPage,
					pageSize: this.pageSize,
					username: this.searchForm.username,
					name: this.searchForm.name
				}
				queryUsersByPage(params).then(res => {
					if (res.data.code == 0) {
						this.total = res.data.data.total;
						this.tableData = res.data.data.list;
					} else {
						Message.error(res.data.msg);
					}
				})
			},
			addUpdateUser(param) {
				if(param != null) {
					this.childData.title = '编辑';
					this.childData.userForm = param;
				}else{
					this.childData.title = '新增';
					this.childData.userForm = null;
				}
				this.childData.visible = true;
				const child = this.$refs.child;
				if (child) {
					child.receiveValues(this.childData);
				}
			},
			refreshPage(){
				this.queryUserListByPage();
			},
			deleteUserList(){
				if(this.multipleSelection.length == 0){
					Message({
						showClose: true,
						message: '请选择数据进行删除！',
						duration: 3000,
						type: 'warning'
					})
				}
				const ids = [];
				this.multipleSelection.forEach(item => {
					ids.push(item.id)
				})
				deleteUsers(ids).then(res => {
					if(res.data.code == 0){
						//刷新页面
						this.queryUserListByPage();
						Message({
							showClose: true,
							message: '删除成功',
							type: 'success'
						})
					}else{
						Message.error(res.data.msg);
					}
				})
				
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			allotRole(row){
				this.allotUserId = row.id;
				queryAllotedRole(this.allotUserId).then(res => {
					if(res.data.code == 0){
						this.$refs.roleTree.setCheckedKeys(res.data.data);
					}
				})
				this.roleTreeTitle = "请为"+row.name+"分配角色";
				this.roleDialogvisible = true;
			},
			queryRoleTreeList(){
				getRoleTree().then(res => {
					if(res.data.code == 0){
						this.treeData = res.data.data;
					}
				})
			},
			saveUserRole(){
				if(this.allotUserId == '' || this.allotUserId == null){
					Message({
						type: 'warning',
						message: '分配角色未获取到用户id，请重新操作',
						showClose: true,
						duration: 3000
					})
				}
				const checkRoles = this.$refs.roleTree.getCheckedNodes();
				const roleIds = []
				checkRoles.forEach(item => {
					roleIds.push(item.id);
				})
				//发送请求保存用户角色信息
				let data = {
					'userId': this.allotUserId,
					'roleIds': JSON.stringify(roleIds),
				}
				saveUserRole(data).then(res => {
					this.$refs.roleTree.setCheckedKeys([]);
					this.roleDialogvisible = false;
					if(res.data.code == 0){
						Message({
							type: 'success',
							message: '保存成功',
							duration: 3000,
						})
					}else{
						Message.error(res.data.msg);
					}
				})
				
			},
			closeRoleTree() {
				this.$refs.roleTree.setCheckedKeys([]);
				this.roleDialogvisible = false;
			}
		},
	}
</script>

<style>
	.user-content {
		height: 100vh;
		background-color: white;
	}

	.table {
		margin: 5px;
	}

	.search {
		margin: 5px;
		float: left;
	}

	.pagina {
		float: right;
		margin-right: 10%;
	}
</style>